package es.mgil.blog;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.internal.StringMap;

public class MainActivity extends Activity implements OnClickListener {
	private EditText etUser;
	private EditText etTitle;
	private EditText etMessage;
	private ListView listView;

	private MensajeAdapter listAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_main);

		findViewById(R.id.buttonSend).setOnClickListener(this);
		findViewById(R.id.buttonRefresh).setOnClickListener(this);

		etUser = (EditText) findViewById(R.id.textUser);
		etTitle = (EditText) findViewById(R.id.textTitle);
		etMessage = (EditText) findViewById(R.id.textMessage);
		listView = (ListView) findViewById(R.id.listView);

		registerForContextMenu(listView);

		listAdapter = new MensajeAdapter(this, R.layout.row);
		listView.setAdapter(listAdapter);

		blogGetMessages();

		// close keyboard
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.layout_main, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case R.id.menu_borrar:
			Mensaje msg = listAdapter.getItem(info.position);
			blogDeleteMessage(msg);
			return true;
		}

		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case (R.id.buttonSend):
			String user = etUser.getText().toString();
			String title = etTitle.getText().toString();
			String message = etMessage.getText().toString();
			blogPutMessage(user, title, message);
			break;
		case (R.id.buttonRefresh):
			blogGetMessages();
			break;
		}

		// close keyboard
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

	private void blogDeleteMessage(Mensaje mensaje) {
		if (mensaje == null) {
			Toast.makeText(MainActivity.this, "No message selected",
					Toast.LENGTH_LONG).show();
			return;
		}

		new AsyncTask<Mensaje, Integer, Boolean>() {
			@Override
			protected Boolean doInBackground(Mensaje... params) {
				try {
					Mensaje msg = params[0];
					String URL_OP3 = new String(
							"http://192.168.0.103:8888/blogM?op=3&id=%s");
					String dURL = String.format(URL_OP3, msg.getId());
					URL url = new URL(dURL);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					new BufferedInputStream(conn.getInputStream());
				} catch (Exception ex) {
					return false;
				}

				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				if (result) {
					Toast.makeText(MainActivity.this, "Message deleted",
							Toast.LENGTH_LONG).show();
					blogGetMessages();
				} else {
					Toast.makeText(MainActivity.this,
							"Cannot delete the message", Toast.LENGTH_LONG)
							.show();
				}
			}
		}.execute(new Mensaje[] { mensaje });
	}

	private void blogPutMessage(final String user, final String title,
			final String message) {
		if (user.isEmpty()) {
			Toast.makeText(MainActivity.this, "Empty user", Toast.LENGTH_LONG)
					.show();
			return;
		}

		if (title.isEmpty()) {
			Toast.makeText(MainActivity.this, "Empty title", Toast.LENGTH_LONG)
					.show();
			return;
		}

		if (message.isEmpty()) {
			Toast.makeText(MainActivity.this, "Empty message",
					Toast.LENGTH_LONG).show();
			return;
		}

		new AsyncTask<Void, Integer, Boolean>() {
			@Override
			protected Boolean doInBackground(Void... params) {
				// Cambiamos espacios por codigos de escape
				String new_usr = user.replaceAll(" ", "%20");
				String new_tit = title.replaceAll(" ", "%20");
				String new_msj = message.replaceAll(" ", "%20");
				String URL_OP2 = new String(
						"http://192.168.0.103:8888/blogM?op=2&user=%s&title=%s&content=%s");
				String sURL = String.format(URL_OP2, new_usr, new_tit, new_msj);
				try {
					URL url = new URL(sURL);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					new BufferedInputStream(conn.getInputStream());
				} catch (Exception ex) {
					return false;
				}

				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				if (result) {
					Toast.makeText(MainActivity.this, "Message sent",
							Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(MainActivity.this,
							"Error sending the message", Toast.LENGTH_LONG)
							.show();
				}
			}
		}.execute();
	}

	private void blogGetMessages() {
		new AsyncTask<Void, Integer, String>() {
			@Override
			protected String doInBackground(Void... params) {
				int BUFFER_SIZE = 2000;
				InputStream in = null;
				String URL_OP1 = new String(
						"http://192.168.0.103:8888/blogM?op=1");
				try {
					URL url = new URL(URL_OP1);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					in = new BufferedInputStream(conn.getInputStream());
				} catch (Exception ex) {
					return null;
				}
				InputStreamReader isr = new InputStreamReader(in);
				int charRead;
				char[] inputBuffer = new char[BUFFER_SIZE];
				try {
					String str = "";
					while ((charRead = isr.read(inputBuffer)) > 0) {
						// ---convert the chars to a String---
						String readString = String.copyValueOf(inputBuffer, 0,
								charRead);
						str += readString;
						inputBuffer = new char[BUFFER_SIZE];
					}
					in.close();
					return str;
				} catch (IOException e) {
					return null;
				}
			}

			@SuppressWarnings("unchecked")
			@Override
			protected void onPostExecute(String result) {
				if (result != null) {
					Gson gson = new Gson();
					List<StringMap<Object>> list = gson.fromJson(result,
							List.class);
					updateMessages(list);
				} else {
					Toast.makeText(MainActivity.this,
							"Error in the connection", Toast.LENGTH_LONG)
							.show();
				}
			}
		}.execute();
	}

	@SuppressWarnings("unchecked")
	private void updateMessages(List<StringMap<Object>> messages) {
		listAdapter.clear();

		for (StringMap<Object> sm : messages) {
			int id = ((Double) sm.get("id")).intValue();
			StringMap<Object> author = (StringMap<Object>) sm.get("author");
			String email = (String) author.get("email");
			String title = (String) sm.get("title");
			String content = (String) sm.get("content");
			String date = (String) sm.get("date");
			boolean owner = email.equals(etUser.getText().toString());

			Mensaje msg = new Mensaje(id, email, title, content, date, owner);
			listAdapter.add(msg);
		}

		listView.setSelection(listAdapter.getCount() - 1);
	}

}
